<template>
  <div id="globalHeader" class="header-container">
    <a-row :wrap="false" class="header-row">
      <a-col flex="300px" class="header-logo-container">
        <RouterLink to="/">
          <div class="title-bar">
            <img class="logo" src="@/assets/logo.svg" alt="logo" />
            <div class="title">智源工坊</div>
          </div>
        </RouterLink>
      </a-col>
      <a-col flex="auto">
        <a-menu
          v-model:selectedKeys="current"
          mode="horizontal"
          :items="items"
          @click="doMenuClick"
          class="header-menu"
        />
      </a-col>
      <a-col flex="180px">
        <div class="user-login-status">
          <div v-if="loginUserStore.loginUser.id">
            <!-- 消息中心按钮 -->
            <a-badge :count="unreadCount" :offset="[-5, 5]">
              <a-button type="text" class="message-button" @click="showMessageCenter">
                <BellOutlined />
              </a-button>
            </a-badge>

            <a-dropdown>
              <ASpace>
                <a-avatar :src="loginUserStore.loginUser.userAvatar" class="avatar">
                  {{ loginUserStore.loginUser.userName?.substring(0, 1).toUpperCase() ?? '无名' }}
                </a-avatar>
              </ASpace>
              <template #overlay>
                <a-menu class="dropdown-menu">
                  <a-menu-item @click="goCenter">
                    <UserOutlined />
                    个人中心
                  </a-menu-item>
                  <a-menu-item @click="doLogout">
                    <LogoutOutlined />
                    退出登录
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
            <span class="user-name">{{ loginUserStore.loginUser.userName ?? '无名' }}</span>
          </div>
          <div v-else>
            <a-button type="primary" class="login-button" href="/user/login">登录</a-button>
          </div>
        </div>
      </a-col>
    </a-row>
  </div>

  <!-- 消息中心抽屉 -->
  <MessageCenter v-model:visible="messageVisible" />
</template>

<script lang="ts" setup>
import { computed, h, onMounted, ref } from 'vue'
import {
  LogoutOutlined,
  UserOutlined,
  BellOutlined,
  BookOutlined,
  FolderOpenOutlined, PlayCircleOutlined
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { useLoginUserStore } from '@/store/user'
import { useRouter } from 'vue-router'
import { userLogout } from '@/api/userController'
import { listAMessageVoByPage } from '@/api/aMessageController'
import checkAccess from '@/utils/access/checkAccess'
import MessageCenter from '@/components/MessageCenter.vue'
import ACCESS_ENUM from '@/utils/access/ACCESS_ENUM'

const loginUserStore = useLoginUserStore()
const current = ref<string[]>([])
const router = useRouter()

const doMenuClick = ({ key }: { key: string }) => {
  router.push({ path: key })
}

router.afterEach((to) => {
  current.value = [to.path]
})

const doLogout = async () => {
  const res = await userLogout()
  if (res.data.code === 0) {
    loginUserStore.setLoginUser({ userName: '未登录' })
    message.success('退出登录成功')
    await router.push('/user/login')
  } else {
    message.error('退出登录失败' + res.data.msg)
  }
}

const menuToRouteItem = (item: any) => {
  return {
    key: item.path,
    label: item.name,
    title: item.name,
    icon: h(item.meta?.icon),
  }
}
const originItems = computed(() => {
  // 确保用户信息已加载且有效
  const currentUser = loginUserStore.loginUser
  if (!currentUser) {
    // 如果用户信息为空，只显示不需要权限的路由
    return router
      .getRoutes()
      .filter((item) => {
        if (item.meta?.hideInMenu) return false
        // 只显示不需要权限的路由（默认为 NOT_LOGIN）
        const needAccess = item.meta?.access || ACCESS_ENUM.NOT_LOGIN
        return needAccess === ACCESS_ENUM.NOT_LOGIN
      })
      .map(menuToRouteItem)
  }
  const routes = router.getRoutes().filter((item) => {
    if (item.meta?.hideInMenu) return false
    return checkAccess(currentUser, item.meta?.access as string)
  })

  // 需要归类到"智慧备课"的路由路径
  const smartPrepPaths = [
    '/teacher/course_design',
    '/teacher/generate_ppt',
    '/teacher/generate_knowledgeGraph',
  ]
  // 需要归类到"我的空间"的路由路径
  const mySpacePaths = [
    '/teacher/collaborative_edit',
    '/teacher/document_diff',
    '/teacher/resourceManagement',
    '/teacher/collaborative_space',
  ]
  // 需要归类到"我的空间"的路由路径
  const multiMediaPaths = [
    '/user/markmap',
    '/teacher/picture_generation',
    '/teacher/video_generation',
  ]

  // 过滤出非智慧备课的路由
  const otherRoutes = routes
    .filter((route) => !smartPrepPaths.includes(route.path))
    .filter((route) => !mySpacePaths.includes(route.path))
    .filter((route) => !multiMediaPaths.includes(route.path))
  // 获取智慧备课相关的路由
  const mySpaceRoutes = routes.filter((route) => mySpacePaths.includes(route.path))
  // 获取智慧备课相关的路由
  const smartPrepRoutes = routes.filter((route) => smartPrepPaths.includes(route.path))
  // 获取多媒体资源教学相关的路由
  const multiMediaRoutes = routes.filter((route) => multiMediaPaths.includes(route.path))
  // 转换其他路由为菜单项
  const otherMenuItems = otherRoutes.map(menuToRouteItem)

  // 如果有智慧备课相关的路由且用户有教师权限，创建智慧备课主菜单
  if (smartPrepRoutes.length > 0 && checkAccess(currentUser, ACCESS_ENUM.TEACHER)) {
    const smartPrepMenuItem = {
      key: 'smart-prep',
      label: '智慧备课',
      title: '智慧备课',
      icon: h(BookOutlined),
      children: smartPrepRoutes.map((route) => ({
        key: route.path,
        label: route.name,
        title: route.name,
        icon: route.meta?.icon ? h(route.meta.icon) : undefined,
      })),
    }

    const mySpaceMenuItem = {
      key: 'my_space',
      label: '资源空间',
      title: '资源空间',
      icon: h(FolderOpenOutlined),
      children: mySpaceRoutes.map((route) => ({
        key: route.path,
        label: route.name,
        title: route.name,
        icon: route.meta?.icon ? h(route.meta.icon) : undefined,
      })),
    }
    const multiMediaMenuItem = {
      key: 'multi_media',
      label: '多媒体教学',
      title: '多媒体教学',
      icon: h(PlayCircleOutlined),
      children: multiMediaRoutes.map((route) => ({
        key: route.path,
        label: route.name,
        title: route.name,
        icon: route.meta?.icon ? h(route.meta.icon) : undefined,
      })),

    }
    return [smartPrepMenuItem, multiMediaMenuItem, mySpaceMenuItem, ...otherMenuItems]
  }

  return otherMenuItems
})

// 使用 computed 来动态生成 items，确保响应性
const items = computed(() => {
  const menuItems = [...originItems.value]

  // 确保主页在第一位
  const homeIndex = menuItems.findIndex((item) => item.key === '/')
  if (homeIndex !== -1) {
    const homeItem = menuItems.splice(homeIndex, 1)[0]
    menuItems.unshift(homeItem)
  }
  return menuItems
})

const goCenter = () => {
  // message.success('感谢你的支持！')
  router.push('/user/center')
}

// 消息中心相关
const messageVisible = ref(false)

// 消息相关数据
const messageList = ref<API.AmessageVO[]>([])
const readMessageIds = ref<Set<number>>(new Set())
const READ_MESSAGES_KEY = 'message_center_read_messages'

// 从localStorage加载已读消息ID
const loadReadMessages = () => {
  try {
    const stored = localStorage.getItem(READ_MESSAGES_KEY)
    if (stored) {
      const ids = JSON.parse(stored)
      readMessageIds.value = new Set(ids)
    }
  } catch (error) {
    console.error('加载已读消息失败:', error)
    readMessageIds.value = new Set()
  }
}

// 检查消息是否已读
const isMessageRead = (messageId: number): boolean => {
  return readMessageIds.value.has(messageId)
}

// 获取未读消息数量
const unreadCount = computed(() => {
  return messageList.value.filter(msg => !isMessageRead(msg.id)).length
})

// 获取消息列表
const fetchMessageList = async () => {
  try {
    const res = await listAMessageVoByPage({
      current: 1,
      pageSize: 50, // 获取更多消息以准确计算未读数量
      allowRole: loginUserStore.loginUser.userRole ?? "student"
    })
    if (res.data.data && res.data.code === 0) {
      messageList.value = res.data.data.records ?? []
    }
  } catch (e) {
    console.error('获取消息列表失败:', e)
  }
}

const showMessageCenter = () => {
  messageVisible.value = true
}

// 确保组件挂载时用户信息已加载
onMounted(async () => {
  // 如果用户信息不完整，尝试重新获取
  if (!loginUserStore.loginUser || !loginUserStore.loginUser.userRole) {
    console.log('组件挂载时用户信息不完整，重新获取用户信息')
    await loginUserStore.fetchLoginUser()
  }
  console.log('组件挂载完成，当前用户:', loginUserStore.loginUser)
  
  // 加载消息相关数据
  loadReadMessages()
  await fetchMessageList()
})
</script>
<style scoped>
/* 整体容器 */
.header-container {
  background-color: rgb(32, 161, 218);
  padding: 0 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  height: 85px;
  position: relative;
  z-index: 100;
}

/* 标题部分 */
.title-bar {
  display: flex;
  align-items: center;
  height: 100%;
}

.logo {
  height: 40px;
  margin-right: 12px;
}

.title {
  font-size: 22px;
  color: white;
  font-weight: 600;
}

/* 深度覆盖 Ant Design 菜单样式 */
:deep(.ant-menu-horizontal) {
  line-height: 85px !important;
  border-bottom: none !important;
  background: transparent !important;
}

:deep(.ant-menu-horizontal > .ant-menu-item),
:deep(.ant-menu-horizontal > .ant-menu-submenu) {
  font-size: 20px !important;
  height: 85px !important;
  line-height: 85px !important;
  /*  padding: 0 20px !important;*/
  /*  margin: 0 3px !important;*/
  color: rgba(255, 255, 255, 0.9) !important;
  transition: all 0.3s ease !important;
}

:deep(.ant-menu-horizontal > .ant-menu-item:hover),
:deep(.ant-menu-horizontal > .ant-menu-submenu:hover) {
  color: white !important;
  background-color: rgba(255, 255, 255, 0.1) !important;
}

:deep(.ant-menu-horizontal > .ant-menu-item-selected) {
  color: white !important;
  font-weight: 600 !important;
  background-color: rgba(255, 255, 255, 0.15) !important;
}

:deep(.ant-menu-horizontal > .ant-menu-item::after),
:deep(.ant-menu-horizontal > .ant-menu-submenu::after) {
  bottom: 1px !important;
}

/* 子菜单样式 */
:deep(.ant-menu-horizontal > .ant-menu-submenu > .ant-menu-submenu-title) {
  font-size: 20px !important;
  height: 85px !important;
  line-height: 85px !important;
  /*  padding: 0 20px !important;*/
  margin: 0 10px !important;
  color: rgba(255, 255, 255, 0.9) !important;
  transition: all 0.3s ease !important;
}

:deep(.ant-menu-horizontal > .ant-menu-submenu > .ant-menu-submenu-title:hover) {
  color: white !important;
  /*  background-color: rgba(255, 255, 255, 0.1) !important;*/
}

/* 下拉菜单容器样式 */
:deep(.ant-menu-submenu-popup) {
  z-index: 1050 !important;
}

:deep(.ant-menu-submenu-popup .ant-menu) {
  background: white !important;
  border-radius: 8px !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15) !important;
  border: 1px solid rgba(0, 0, 0, 0.06) !important;
}

/* 下拉菜单项样式 */
:deep(.ant-menu-submenu-popup .ant-menu-item) {
  padding: 12px 20px !important;
  margin: 4px 8px !important;
  border-radius: 6px !important;
  color: #333 !important;
  font-size: 16px !important;
  line-height: 1.5 !important;
  height: auto !important;
  transition: all 0.2s ease !important;
}

:deep(.ant-menu-submenu-popup .ant-menu-item:hover) {
  background-color: #f0f9ff !important;
  color: rgb(32, 161, 218) !important;
}

:deep(.ant-menu-submenu-popup .ant-menu-item-selected) {
  background-color: #e0f2fe !important;
  color: rgb(32, 161, 218) !important;
  font-weight: 500 !important;
}

/* 用户信息区域 */
.user-login-status {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  height: 100%;
  gap: 20px;
}

.user-login-status > div {
  display: flex;
  align-items: center;
  gap: 16px;
}

/* 消息按钮样式 */
.message-button {
  color: white !important;
  font-size: 20px !important;
  height: 42px !important;
  width: 42px !important;
  border-radius: 50% !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  transition: all 0.3s ease !important;
  background: rgba(255, 255, 255, 0.1) !important;
  border: none !important;
}

.message-button:hover {
  background: rgba(255, 255, 255, 0.2) !important;
  transform: scale(1.1) !important;
  color: white !important;
}

.avatar {
  width: 42px;
  height: 42px;
  line-height: 42px;
  background-color: rgba(255, 255, 255, 0.2);
  color: white;
}

.user-name {
  color: white;
  font-size: 18px;
  margin-left: 10px;
}

.login-button {
  height: 42px;
  /*padding: -2px 16px;*/
  font-size: 18px;
  background-color: white;
  color: rgb(48, 164, 173);
  border-radius: 21px;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .header-container {
    padding: 0 12px;
  }

  :deep(.ant-menu-horizontal > .ant-menu-item),
  :deep(.ant-menu-horizontal > .ant-menu-submenu) {
    font-size: 16px !important;
    padding: 0 12px !important;
  }

  .user-name {
    display: none;
  }

  .message-button {
    width: 36px !important;
    height: 36px !important;
    font-size: 16px !important;
  }
}
</style>
